<?php
namespace app\erp_meixingtiyu\logic;

use app\erp_meixingtiyu\model\CourseLesson as CourseLessonModel;
use \DateTime;

class CourseLesson
{
    public function getList($courseId)
    {
        $list = (new CourseLessonModel())->selectAllLessonsByCourseId(
            $courseId
        );
        return $list->toArray();
    }

    public function addLesson($data)
    {
        (new CourseLessonModel())->createLesson($data);
    }

    public function editLesson($data)
    {
        (new CourseLessonModel())->updateLesson($data);
    }

    public function deleteLesson($lessonId)
    {
        // 判断课时是否已开始，已开始则不能删除
        $course = CourseLessonModel::getLessonById($lessonId);
        if ($course->isEmpty()) {
            throwError('该课程不存在');
        }
        if ($this->hasStarted($course)) {
           throwError('已经开始的课程不能删除哦');
        }
        $course->delete();
    }

    public function hasStarted($courseModel)
    {
        $class_time =
            $courseModel->class_date .
            ' ' .
            explode('-', $courseModel->class_time)[0];
        $dateTime = DateTime::createFromFormat('Y-m-d h:i', $class_time);
        $interval = (new DateTime())->diff($dateTime);

        if ($interval->invert == 1) {
            return true;
        }

        return false;
    }
}
